﻿using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Ewell.Interface.Common.Utils
{
    public static class ObjectExtend
    {
        public static Destination CopyProperties<Destination>(this object source)
            where Destination : class, new()
        {
            Destination result=default;
            return source.CopyProperties(result);
        }
        public static Destination CopyProperties<Destination>(this object source, Destination destination)
            where Destination : class,new()
        {
            if (destination == null) destination = new Destination();
            var sourceProperties = source.GetType().GetProperties().ToDictionary(p => p.Name, p => p, StringComparer.OrdinalIgnoreCase);

            var destinationProperties = typeof(Destination).GetProperties().ToDictionary(p => p.Name, p => p, StringComparer.OrdinalIgnoreCase);

            foreach (var sourceProperty in sourceProperties)
            {
                if (destinationProperties.TryGetValue(sourceProperty.Key, out PropertyInfo destinationProperty))
                {
                    if (sourceProperty.Value.PropertyType == destinationProperty.PropertyType)
                    {
                        destinationProperty.SetValue(destination, sourceProperty.Value.GetValue(source));
                    }
                    else
                    {
                        try
                        {
                            object value = Convert.ChangeType(sourceProperty.Value.GetValue(source), destinationProperty.PropertyType);
                            destinationProperty.SetValue(destination, value);
                        }
                        catch (InvalidCastException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            return destination;
        }
        public static void CopyProperties<Source, Destination>(Source source, Destination destination)
            where Source : class where Destination : class,new()
        {
            source.CopyProperties(destination);
        }
    }
}
